﻿using JinianNet.JNCms;
using JinianNet.JNCms.Data;
using JinianNet.JNCms.Models;
using System;
using System.Collections;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;

namespace JinianNet.JNCms.Api
{
    public class DiscuzNTController : JinianNet.JNCms.Controllers.ControllerBase
    {
        public ActionResult Action()
        {
            //System.IO.File.AppendAllText(Server.MapPath("~/test.txt"),"请求成功"+Request.QueryString.ToString()+Request.QueryString.ToString());
            //return Content("成功");

            switch (Request.QueryString["action"])
            {
                case "login"://登录
                    return ReturnXmlAction(Login(Request.QueryString["user_name"]));
                case "logout"://签出
                    return ReturnXmlAction(Logout());
                case "updatepwd"://密码
                    return ReturnXmlAction(UpdatePassword(Request.QueryString["user_name"], Request.QueryString["password"]));
                case "updatecredits"://积分
                    return ReturnXmlAction(UpdateCredits(Request.QueryString["uid"], Request.QueryString["credit_index"], Request.QueryString["amount"]));
                case "register"://注册
                    return ReturnXmlAction(Register(Request.QueryString["uid"], Request.QueryString["user_name"], Request.QueryString["password "]));
                case "updateprofile"://更新用户资料
                    return ReturnXmlAction(UpdateProfile(Request.QueryString["uid"], Request.QueryString["user_name"]));
                default:
                    var hash = new Hashtable();
                    hash["success"] = false;
                    hash["msg"] = string.Concat("操作失败，接口未实现,参数:" ,Request.QueryString.ToString());
                    return ReturnXmlAction(hash);
            }
        }

        private ActionResult ReturnXmlAction(Hashtable hash)
        {
            string result = (string.Concat("<?xml version=\"1.0\" encoding=\"utf-8\"?><Result><Success>",
                (bool)hash["success"] ? "1" : "0",
                "</Success><Msg><![CDATA[ ",
                hash["msg"].ToString(),
                " ]]></Msg></Result>"));
            Write(result);

            return Content(result);
        }

        private Hashtable UpdateProfile(string id, string account)
        {
            Hashtable hash = new Hashtable();
            hash["success"] = false;
            hash["msg"] = "操作失败，接口未实现";
            return hash;
        }

        private Hashtable Register(string id, string account, string password)
        {
            Hashtable hash = new Hashtable();
            IUsers dal = Data.DataAccess.CreateUsers();

            Users model = new Users();
            model.Account = account;
            model.Answer = "";
            model.Balance = 0;
            model.CurrentLoginIP = "";
            model.CurrentLoginTime = DateTime.Now;
            model.Email = JinianNet.JNCms.Config.Email.Mail;
            model.EnableResetPassword = true;
            model.EndTime = DateTime.Now.AddYears(100);
            model.FaceHeight = 100;
            model.FaceWidth = 100;
            model.FailedPasswordAnswerAttempCount = 0;
            model.FailedPasswordAttemptCount = 0;
            model.GetPasswordSid = "";
            model.GetPasswordTime = DateTime.Now;
            model.GroupID = 0;
            model.HonorType = 0;
            model.ID = int.Parse(id);
            model.IDCard = "";
            model.IsAdministrator = false;
            model.IsInheritGroupRole = true;
            model.JoinTime = DateTime.Now;
            model.LastFailedPasswordAnswerAttempTime = DateTime.Now;
            model.LastFailedPasswordAttempTime = DateTime.Now;
            model.LastLockoutTime = DateTime.Now;
            model.LastLoginIP = "";
            model.LastLoginTime = DateTime.Now;
            model.LastPasswordChangedTime = DateTime.Now;
            model.LastPresentTime = DateTime.Now;
            model.LoginCount = 0;
            model.NickName = account;
            model.PrivacySetting = 0;
            model.Question = "";
            model.RegTime = DateTime.Now;
            model.Sex = 0;
            model.Sign = "";
            model.Status = 0;
            model.UserExp = 0;
            model.UserFace = "";
            model.UserName = account;
            model.UserPassword = password;
            model.UserPermission = "";
            model.UserPoint = 0;
            model.UserType = 0;
            if (dal.Insert(model) > 0)
            {
                hash["success"] = true;
                hash["msg"] = "操作成功";
            }
            else
            {
                hash["success"] = false;
                hash["msg"] = "操作失败，请重试";
            }
            return hash;
        }

        private Hashtable UpdateCredits(string id, string index, string amount)
        {
            Hashtable hash = new Hashtable();
            int iID, iIndex, iAmount;
            if (int.TryParse(id, out iID) && int.TryParse(index, out iIndex) && int.TryParse(amount, out iAmount))
            {
                IUsers dal = Data.DataAccess.CreateUsers();

                Users model = dal.GetItem(iID);
                if (model != null)
                {
                    if (iIndex == 1)
                    {
                        model.UserPoint += iAmount;
                        hash["success"] = true;
                        hash["msg"] = "操作成功";
                        return hash;
                    }
                    else if (iIndex == 2)
                    {
                        model.UserExp += iAmount;
                        hash["success"] = true;
                        hash["msg"] = "操作成功";
                        return hash;
                    }
                }
            }
            hash["success"] = false;
            hash["msg"] = "操作失败,参数有误";
            return hash;
        }

        private Hashtable UpdatePassword(string account, string password)
        {
            Hashtable hash = new Hashtable();
            IUsers dal = Data.DataAccess.CreateUsers();
            if (dal.UpdatePassword(account, password) > 0)
            {
                hash["success"] = true;
                hash["msg"] = "操作成功";
            }
            else
            {
                hash["success"] = false;
                hash["msg"] = "操作失败";
            }

            return hash;
        }

        private Hashtable Logout()
        {
            Session.Remove("User");
            System.Web.HttpCookie authCookie = new System.Web.HttpCookie("User", "");
            authCookie.Expires = DateTime.Now.AddYears(-1);
            ControllerContext.HttpContext.Response.Cookies.Add(authCookie);
            Hashtable hash = new Hashtable();
            hash["success"] = true;
            hash["msg"] = "登出成功";
            return hash;
        }

        private Hashtable Login(string name)
        {
            Hashtable hash = new Hashtable();
            IUsers dal = Data.DataAccess.CreateUsers();
            Users model = dal.GetItem(name);
            if (model == null)
            {
                hash["success"] = false;
                hash["msg"] = "用户不存在";
            }
            else
            {
                dal.LoginSuccess(model.Account, Common.Utils.GetIP(), DateTime.Now);
                Session["User"] = model;
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                                 1,
                                 "User",
                                 DateTime.Now,
                                 DateTime.Now.AddMinutes(30),
                                 false,
                                 model.Account);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                System.Web.HttpCookie authCookie = new System.Web.HttpCookie("User", encryptedTicket);
                ControllerContext.HttpContext.Response.Cookies.Add(authCookie);
                hash["success"] = true;
                hash["msg"] = "登录成功";
            }

            return hash;
        }

        private void Write(string msg)
        {
            System.IO.FileInfo info = new System.IO.FileInfo(Server.MapPath(string.Concat("~/Log/", DateTime.Now.ToString("yyyyMMdd"), ".txt")));
            if (!info.Directory.Exists)
            {
                info.Directory.Create();
            }
            System.IO.File.AppendAllText(info.FullName, string.Concat("\r\n", DateTime.Now.ToString(), "\r\n", msg, "\r\n-------------------------------------------------------------------------\r\n\r\n"));
        }
    }
}


/*
 * 
 * 关键词
事件
返回参数
(不包括action和time)
login
登录
uid  用户ID
user_name 用户名
logout
登出
uid  用户ID
deleteuser
后台删除用户
uids 用户ID列表(逗号分割)
renameuser
后台用户重命名
new_user_name 新的用户名
old_user_name旧的用户名
uid  用户ID
updatepwd
用户修改密码
password  加密后的密码
user_name  用户名
updatecredits
更新用户积分
amount操作数值
credit_index 扩展积分索引
uid  用户ID
updatesignature  
修改签名
signature  签名内容
uid  用户ID
user_name  用户名
newtopic
发新主题
author作者用户名
author_id作者ID
fid板块id
tid主题id
title  标题
reply
回复
fid  板块id
pid  帖子id
poster   帖子作者
poster_id  帖子作者ID
tid 帖子所在主题id
topic_title  主题标题
register
注册
uid  用户ID
user_name  用户名
password  加密后的密码
updateprofile
更新用户资料
uid  用户ID
user_name  用户名
 * 
 * 
 * 
 * 
 * 
 */